import { defineStore } from "pinia";
import { ref } from "vue";
import { getKeyAndPassword } from "@/utils/jsencrypt";
import { nanoid } from 'nanoid'
import type UserInfo from "@/types/UserInfo";
import { getPublicKey, doLogin, doLogout } from "@/api/login";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/userStore";
import type JsonResult from "@/types/JsonResult";
import { useRouter } from "vue-router";

/**
 * 登录仓库
 */
export const useLoginStore = defineStore("loginStore", () => {
    /**
     * 登录状态
     * false:未登录
     * true:已登录
     */
    const loginState = ref(false)
    /**
     * 登录组件显隐，和登录状态挂钩
     */
    const loginDisplay = ref(false)

    const userStore = useUserStore()

    const router = useRouter()

    /**
     * 登录逻辑
     */
    const login = async (userInfo: UserInfo) => {

        const { data } = await getPublicKey()
        data.state == 200 ? commit(data.data,userInfo) : ElMessage.warning("公钥拉取失败,请检查网络连接")

    }

    /**
     * 提交登录表单数据
     * @param publicKey 公钥
     * @param userInfo 用户表单信息
     */
    const commit = async (publicKey:string,userInfo:UserInfo) => {
        //1.加密
        const keyPassword = getKeyAndPassword(publicKey,userInfo.password)
        userInfo.key = keyPassword[0]
        userInfo.password = keyPassword[1]
        //2.生成一个uid，作为设备唯一标识
        //(现在服务器并没有使用，因此暂不做任何存储等处理，单纯生成即可)
        userInfo.uid = nanoid()
        //3.登录-提交表单信息
        const {data} = await doLogin(userInfo)
        if (data.state == 200) {
            loginState.value = true
            loginDisplay.value = false
            Object.assign(userStore.user,data.data)
            ElMessage.success("登录成功")
        } else {
            //清理密码输入
            userInfo.password = ""
            ElMessage.warning(data.message)
        }
    }

    /**
     * 登出
     */
    const logout = async () => {
        const {data} = await doLogout(userStore.user.id)

        data.state==200? logout_success(data):logout_failed(data)
    }

    /**
     * 登录成功逻辑
     */
    const logout_success = (data:JsonResult)=>{
        //修改登录状态
        loginState.value = false
        //删除本地内存中的用户信息
        localStorage.removeItem("user_store");
        //跳转首页
        router.push("/index")
        ElMessage.success("登出成功!")
    }
    /**
     * 登录失败逻辑
     */
    const logout_failed = (data:JsonResult)=>{
        ElMessage.warning(data.message)   
    }

    return { loginState, loginDisplay, login,logout}
}, {
    persist: {
        // 存储的key,默认使用localStorage进行存储
        key: 'login_store',
        // 被持久化的值
        paths: ['loginState']
    }
})